package com.quzi.kettle.activitise;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.quzi.kettle.R;
import com.quzi.kettle.socket.SocketRequest;

public class SocketActivity extends Activity {

	private EditText ipaddr, port, cmd;
	private Button connect, send;

	private TextView textView;
	private SocketRequest request;
	private Handler UIHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_socket);

		ipaddr = (EditText) findViewById(R.id.ipaddr);
		port = (EditText) findViewById(R.id.port);
		cmd = (EditText) findViewById(R.id.cmd);
		connect = (Button) findViewById(R.id.connect);
		send = (Button) findViewById(R.id.send);

		textView = (TextView) findViewById(R.id.textView1);
		initHandler();

		connect.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new Thread(new Runnable() {
					@Override
					public void run() {
						getRequest().connection2Service();
					}
				}).start();
			}
		});

		send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				// TODO Auto-generated method stub
				getRequest().writeCMD(cmd.getText().toString().getBytes());

			}
		});

	}

	private void initHandler() {
		// TODO Auto-generated method stub
		UIHandler = new Handler() {
			@Override
			public void dispatchMessage(Message msg) {
				// TODO Auto-generated method stub
				super.dispatchMessage(msg);

				textView.setText(msg.toString());

			}
		};
	}

	private SocketRequest getRequest() {
		if (request == null) {
			request = SocketRequest.getInstance(ipaddr.getText().toString(),
					Integer.valueOf(port.getText().toString()), UIHandler);
		}
		return request;
	}
}
